package com.ztom.v2;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author ZhangTao
 */
public class Code58CombinationSum {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return new ArrayList<>();
        }

        List<List<Integer>> res = new ArrayList<>();
        dfs(candidates, target, 0, new LinkedList<>(), res);
        return res;
    }

    public void dfs(int[] candidates, int target, int index, Deque<Integer> path, List<List<Integer>> res) {
        if (index >= candidates.length || target < 0) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }

//        // 取当前的数
//        if (target >= candidates[index]) {
//            path.addLast(candidates[index]);
//            // index 不变, 因为每个数可以重复取多次
//            dfs(candidates, target - candidates[index], index, path, res);
//            path.pollLast();
//        }
//        // 不取当前的数
//        dfs(candidates, target, index + 1, path, res);

        for (int i = index; i < candidates.length; i++) {
            if (target < candidates[i]) {
                continue;
            }
            path.addLast(candidates[i]);
            // i 不变, 因为每个数可以重复取多次
            dfs(candidates, target - candidates[i], i, path, res);
            path.pollLast();
        }
    }
}
